/** 玩家控制器，用来监听键盘输入，从而控制玩家 */
export default class PlayerController {
    constructor(player) {
        this.player = player;

        this.bindListener();

        // 记录被按下的按键情况，true表示该按键被按下
        this.reflectKeyMap = {
            w: false,
            a: false,
            s: false,
            d: false,
        };
    }

    bindListener() {
        let _this = this;
        document.addEventListener('keydown', function (event) {
            _this.reflectKeyMap[event.key] = true;
        });

        document.addEventListener('keyup', function (event) {
            _this.reflectKeyMap[event.key] = false;
            if (['w', 's'].includes(event.key)) {
                _this.player && _this.player.stopMoveY();
            }
            if (['a', 'd'].includes(event.key)) {
                _this.player && _this.player.stopMoveX();
            }
        });
    }

    moveUp() {
        this.player && this.player.moveY(false);
    }

    moveDown() {
        this.player && this.player.moveY(true);
    }

    moveLeft() {
        this.player && this.player.moveX(false);
    }

    moveRight() {
        this.player && this.player.moveX(true);
    }

    update() {
        if (this.reflectKeyMap['w']) this.moveUp();
        if (this.reflectKeyMap['a']) this.moveLeft();
        if (this.reflectKeyMap['s']) this.moveDown();
        if (this.reflectKeyMap['d']) this.moveRight();
    }
}
